//
//  LSAttendanceRecordsDetailViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2019/5/20.
//  Copyright © 2019 wpkj. All rights reserved.
//

#import "LSAttendanceRecordsDetailViewController.h"
#import "LSInfoCollectTableViewCell.h"

#define FontSize 14

@interface LSAttendanceRecordsDetailViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UITextViewDelegate>
@property (nonatomic, strong) NSMutableArray *infoTitleLabelArrayM;
@property (nonatomic, strong) UITableView *approveTableView;
@property (nonatomic, strong) UIView *tableViewFooterView;
@property (nonatomic, strong) UITextField *approveStateTF;
@property (nonatomic, strong) NSArray *approveStateTFArray;
@property (nonatomic, strong) UITextView *contentTV;
@property (nonatomic, strong) NSArray *shenpiArray;
@end

static NSString *LSInfoCollectTableViewCellID = @"LSInfoCollectTableViewCellID";

@implementation LSAttendanceRecordsDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    switch (self.approveType) {
        case 1:
            self.title = @"请假详情";
            break;
        case 2:
            self.title = @"出差详情";
            break;
        case 3:
            self.title = @"用车详情";
            break;
        default:
        {
            [MBProgressHUD showTipMessageInWindow:@"状态错误"];
            [self.navigationController popViewControllerAnimated:true];
        }
            break;
    }
    [self.view addSubview:self.approveTableView];
    [self loadData];
}

- (void)requestListForLabel:(UILabel *)label forKeyTitle:(NSString *)key withURLString:(NSString *)URLString andParam:(NSDictionary *)param listCode:(NSString *)listCode showCode:(NSString *)showCode requestCode:(NSString *)requestCode {
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:URLString param:param completionHandler:^(id responseObject, NSError *connectionError) {
        if (!connectionError) {
            NSLog(@"返回数据----%@",responseObject);
            NSArray *objArray = [responseObject objectForKey:listCode];
            if (objArray && objArray.count > 0) {
                NSMutableArray *objArrayM = [[NSMutableArray alloc] initWithArray:objArray];
                for (NSDictionary *dict in objArrayM) {
                    if ([dict[requestCode] isEqualToString:key]) {
                        label.text = dict[showCode];
                    }
                }
            }
        } else {
            [MBProgressHUD showTipMessageInWindow:[NSString stringWithFormat:@"%@",connectionError.localizedDescription]];
        }
    }];
}

- (void)setUpHeaderViewWithDict:(NSDictionary *)responsObject {
    NSArray *dataArray = [responsObject objectForKey:@"data"];
    NSArray *awayArray = [responsObject objectForKey:@"away"];
    NSDictionary *dataDict = @{};
    if (dataArray && dataArray.count > 0) {
        dataDict = dataArray.firstObject;
    }
    
    UIView *headerInfoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 44*self.tipTitleLabelArray.count+40)];
    headerInfoView.backgroundColor = UIColor.whiteColor;
    
    CGFloat currentHeight = 0.0f;
    for (int i = 0; i < self.tipTitleLabelArray.count; i++) {
        UILabel *tipTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 8+(44-8-15)/2+currentHeight, 100, 20)];
        tipTitleLabel.text = self.tipTitleLabelArray[i];
        tipTitleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:14];
        tipTitleLabel.textColor = hexColor(333333);
        [tipTitleLabel sizeToFit];
        [headerInfoView addSubview:tipTitleLabel];
        
        UILabel *infoTitleLabel = [[UILabel alloc] init];
        infoTitleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:14];
        infoTitleLabel.textColor = hexColor(333333);
        [headerInfoView addSubview:infoTitleLabel];
        infoTitleLabel.text = [ValidateUtils validateNull:dataDict[self.infoTitleLabelArray[i]]];
        if ((i == self.tipTitleLabelArray.count - 2 && [self.fromVC isEqualToString:@"考勤列表"]) || (i == self.tipTitleLabelArray.count - 1 && [self.fromVC isEqualToString:@"消息中心"])) {// 倒数第二个，显示审批状态
            switch (self.approveState) {
                case 1:
                    infoTitleLabel.text = @"待审批";
                    break;
                case 2:
                    infoTitleLabel.text = @"同意";
                    break;
                case 3:
                    infoTitleLabel.text = @"不同意";
                    break;
                case 4:
                    infoTitleLabel.text = @"已撤销";
                    break;
                default:
                    infoTitleLabel.text = @"待审批";
                    break;
            }
        }
        if (self.approveType == 1 && i == 4) {//请假
            [self requestListForLabel:infoTitleLabel forKeyTitle:[ValidateUtils validateNull:dataDict[self.infoTitleLabelArray[i]]] withURLString:OASjzd andParam:@{@"typeGroupName":@"leave",@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token]} listCode:@"obj" showCode:@"typename" requestCode:@"typecode"];
        }
        if ([[ValidateUtils validateNull:self.tipTitleLabelArray[i]] rangeOfString:@"时长"].length > 0) {
            infoTitleLabel.text = [NSString stringWithFormat:@"%.2f小时",[ValidateUtils validateNull:dataDict[self.infoTitleLabelArray[i]]].floatValue];
        }
        if ([[ValidateUtils validateNull:self.tipTitleLabelArray[i]] rangeOfString:@"公里数"].length > 0) {
            infoTitleLabel.text = [NSString stringWithFormat:@"%.1f公里数",[ValidateUtils validateNull:dataDict[self.infoTitleLabelArray[i]]].floatValue];
        }
        if ([[ValidateUtils validateNull:self.tipTitleLabelArray[i]] rangeOfString:@"事由"].length > 0 || [[ValidateUtils validateNull:self.tipTitleLabelArray[i]] rangeOfString:@"备注"].length > 0 || [[ValidateUtils validateNull:self.tipTitleLabelArray[i]] rangeOfString:@"意见"].length > 0 || [[ValidateUtils validateNull:self.tipTitleLabelArray[i]] rangeOfString:@"费用支付单位"].length > 0 || [[ValidateUtils validateNull:self.tipTitleLabelArray[i]] rangeOfString:@"出差地点："].length > 0) {
            CGRect TitleRect = [[ValidateUtils validateNull:dataDict[self.infoTitleLabelArray[i]]] boundingRectWithSize:CGSizeMake(ScreenWidth-45, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont fontWithName:@"SourceHanSansCN-Regular" size:14]} context:nil];
            [infoTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(headerInfoView.mas_left).with.offset(30);
                make.top.equalTo(tipTitleLabel.mas_bottom).with.offset(8);
                make.right.equalTo(headerInfoView.mas_right).with.offset(-15);
                make.height.mas_equalTo(TitleRect.size.height+8+12);
            }];
            infoTitleLabel.numberOfLines = 0;
            currentHeight += TitleRect.size.height+8+12+8+8+(44-8-15);
            if ([[ValidateUtils validateNull:self.tipTitleLabelArray[i]] rangeOfString:@"出差地点："].length > 0) {
                currentHeight -= 30;
                for (NSDictionary *dict in awayArray) {
                    UILabel *beginLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, currentHeight, (ScreenWidth-45)/2, 15) andText:[NSString stringWithFormat:@"出发地：%@",[ValidateUtils validateNull:dict[@"AWAY_START"]]] andTextColor:hexColor(999999) andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:14] andTextAlignment:NSTextAlignmentLeft];
                    UILabel *endLabel = [[UILabel alloc] initWithFrame:CGRectMake(30+(ScreenWidth-45)/2, currentHeight, (ScreenWidth-45)/2, 15) andText:[NSString stringWithFormat:@"目的地：%@",[ValidateUtils validateNull:dict[@"AWAY_END"]]] andTextColor:hexColor(999999) andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:14] andTextAlignment:NSTextAlignmentLeft];
                    [headerInfoView addSubview:beginLabel];
                    [headerInfoView addSubview:endLabel];
                    currentHeight += 15+8;
                    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(15, currentHeight, ScreenWidth-30, 0.5)];
                    lineView.backgroundColor = hexColor(dbdbdb);
                    [headerInfoView addSubview:lineView];
                }
            } else {
                UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(15, currentHeight, ScreenWidth-30, 0.5)];
                lineView.backgroundColor = hexColor(dbdbdb);
                [headerInfoView addSubview:lineView];
            }
        } else {
            [infoTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(tipTitleLabel.mas_right).with.offset(2);
                make.centerY.equalTo(tipTitleLabel.mas_centerY);
                make.right.equalTo(headerInfoView.mas_right).with.offset(-12);
                make.height.equalTo(@20);
            }];
            currentHeight += 44;
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(15, currentHeight, ScreenWidth-30, 0.5)];
            lineView.backgroundColor = hexColor(dbdbdb);
            [headerInfoView addSubview:lineView];
        }
    }
    headerInfoView.frame = CGRectMake(0, 0, ScreenWidth, currentHeight+40);
    self.approveTableView.tableHeaderView = headerInfoView;
}

- (void)loadData {
    NSString *URLString = @"";
    switch (self.approveType) {
        case 1:
            URLString = AskForLeaveDetail;
            break;
        case 2:
            URLString = BusinessTripDetail;
            break;
        case 3:
            URLString = CarUsageDetial;
            break;
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:URLString param:@{@"id":self.listID,@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token]} completionHandler:^(id responseObject, NSError *connectionError) {
        [hud hideAnimated:true];
        NSNumber *status = [responseObject objectForKey:@"status"];
        if (status.integerValue == 200) {
            NSArray *dataArray = [responseObject objectForKey:@"data"];
            if (dataArray && dataArray.count > 0) {
                NSDictionary *dataDict = dataArray.firstObject;
//                NSNumber *APPROVE_TYPE = dataDict[@"APPROVE_TYPE"];
                if (self.approveState == 2) {
                    self.approveStateTF.text = @"同意";
                    self.contentTV.text = [ValidateUtils validateNull:dataDict[@"APPROVE_MAIN"]];
                } else if (self.approveState == 3) {
                    self.approveStateTF.text = @"不同意";
                    self.contentTV.text = [ValidateUtils validateNull:dataDict[@"APPROVE_MAIN"]];
                } else if (self.approveState == 1) {
                    if ([self.fromVC isEqualToString:@"消息中心"]) {
                        self.approveStateTF.text = @"待审批";
                    }
                } else if (self.approveState == 4) {
                    self.approveStateTF.text = @"已撤销";
                    self.contentTV.text = [ValidateUtils validateNull:dataDict[@"APPROVE_MAIN"]];
                }
                [self setUpHeaderViewWithDict:responseObject];
            }
        } else {
            [MBProgressHUD showTipMessageInWindow:[ValidateUtils validateNull:responseObject[@"message"]]];
        }
    }];
}

#pragma mark - 提交按钮点击事件
- (void)submitButtonClick {
    if ([self.approveStateTF.text isEqualToString:@""] || [self.approveStateTF.text isEqualToString:@"请选择"]) {
        [MBProgressHUD showTipMessageInWindow:@"请选择审批状态"];
        return;
    } else if ([[ValidateUtils validateNull:self.contentTV.text] isEqualToString:@""]) {
        [MBProgressHUD showTipMessageInWindow:@"请填写审批意见"];
        return;
    }
    NSString *APPROVE_STATEString = @"";
    if ([self.approveStateTF.text isEqualToString:@"同意"]) {
        APPROVE_STATEString = @"2";
    } else {
        APPROVE_STATEString = @"3";
    }
    NSDictionary *param = @{@"id":self.listID,@"APPROVE_STATE":APPROVE_STATEString,@"APPROVE_OPINION":self.contentTV.text,@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token]};
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:OAApprove param:param completionHandler:^(id responseObject, NSError *connectionError) {
        if (!connectionError) {
            NSLog(@"返回数据----%@",responseObject);
            NSNumber *status = [responseObject objectForKey:@"status"];
            if (status.integerValue == 200) {
                [MBProgressHUD showTipMessageInWindow:[responseObject objectForKey:@"message"]];
                if (self.refreshBlock) self.refreshBlock();
                WS
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf.navigationController popViewControllerAnimated:true];
                });
            } else {
                [MBProgressHUD showTipMessageInWindow:[responseObject objectForKey:@"message"]];
            }
        } else {
            [MBProgressHUD showTipMessageInWindow:[NSString stringWithFormat:@"%@",connectionError.localizedDescription]];
        }
    }];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == self.approveStateTF) {
        if (self.approveState == 1) [self showSelectControllerForTextField:self.approveStateTF WithContentArray:self.approveStateTFArray];
        return false;
    }
    return false;
}

#pragma mark - 弹窗
- (void)showSelectControllerForTextField:(UITextField *)textField WithContentArray:(NSArray *)contentArray {
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (int i = 0; i < contentArray.count; i++) {
        [alertC addActionTarget:alertC title:contentArray[i] color:NAV_COLOR action:^(UIAlertAction *action) {
            textField.text = contentArray[i];
        }];
    }
    [alertC addCancelActionTarget:alertC color:NAV_COLOR title:@"取消"];
    [self presentViewController:alertC animated:true completion:nil];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if (!(([ValidateUtils isInputRuleNotBlank:text] && ![ValidateUtils hasSpecialString:text]) || [text isEqualToString:@""])) {//当输入符合规则和退格键时允许改变输入框
        return NO;
    } else {
        if (textView == self.contentTV && (text.length == 0 || [text isEqualToString:@""])) return TRUE;
        if (textView == self.contentTV && textView.text.length > 499) return FALSE;
        return TRUE;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([self.fromVC isEqualToString:@"待办列表"]) {
        return self.shenpiArray.count;
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSInfoCollectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LSInfoCollectTableViewCellID forIndexPath:indexPath];
    cell.leftLabel.text = self.shenpiArray[indexPath.row];
    [cell.leftLabel sizeToFit];
    LSInfoCollectTableViewCell *currentCell = cell;
    if (indexPath.row == 0) {
        [currentCell.contentView addSubview:self.approveStateTF];
        [self.approveStateTF mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(currentCell.leftLabel.mas_right).with.offset(12);
            make.right.equalTo(currentCell.contentView.mas_right).with.offset(-15);
            make.top.equalTo(currentCell.contentView.mas_top).with.offset(8);
            make.bottom.equalTo(currentCell.contentView.mas_bottom);
        }];
    } else if (indexPath.row == 1) {
        [currentCell.contentView addSubview:self.contentTV];
        [self.contentTV mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(currentCell.contentView.mas_left).with.offset(15);
            make.right.equalTo(currentCell.contentView.mas_right).with.offset(-15);
            make.top.equalTo(currentCell.leftLabel.mas_bottom).with.offset(8);
            make.bottom.equalTo(currentCell.contentView.mas_bottom).with.offset(-8);
        }];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 1) {
        return 150;
    }
    return 44;
}

- (UITableView *)approveTableView {
    if (!_approveTableView) {
        _approveTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight)];
        _approveTableView.delegate = self;
        _approveTableView.dataSource = self;
        [_approveTableView registerClass:LSInfoCollectTableViewCell.class forCellReuseIdentifier:LSInfoCollectTableViewCellID];
        _approveTableView.separatorInset = UIEdgeInsetsZero;
        _approveTableView.tableFooterView = [UIView new];
        _approveTableView.backgroundColor = hexColor(EEEEEE);
        if (self.approveState == 1 && [self.fromVC isEqualToString:@"待办列表"]) {
            _approveTableView.tableFooterView = self.tableViewFooterView;
        }
    }
    return _approveTableView;
}

- (UIView *)tableViewFooterView {
    if (!_tableViewFooterView) {
        _tableViewFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 100)];
        UIButton *submitButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 30, ScreenWidth-30, 40)];
        [submitButton setTitle:@"提交" forState:UIControlStateNormal];
        [submitButton setTitleColor:hexColor(ffffff) forState:UIControlStateNormal];
        submitButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:14];
        submitButton.backgroundColor = hexColor(FDBB2C);
        submitButton.layer.cornerRadius = 4;
        submitButton.layer.masksToBounds = true;
        [submitButton addTarget:self action:@selector(submitButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_tableViewFooterView addSubview:submitButton];
    }
    return _tableViewFooterView;
}

- (UITextField *)approveStateTF {
    if (!_approveStateTF) {
        _approveStateTF = [[UITextField alloc] init];
        _approveStateTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:FontSize];
        UIImageView *approveStateTFRightViewImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 44-8, 44-8)];
        approveStateTFRightViewImageView.contentMode = UIViewContentModeCenter;
        approveStateTFRightViewImageView.image = [UIImage imageNamed:@"xiala"];
        _approveStateTF.rightView = approveStateTFRightViewImageView;
        _approveStateTF.rightViewMode = UITextFieldViewModeAlways;
        _approveStateTF.delegate = self;
        _approveStateTF.text = @"请选择";
    }
    return _approveStateTF;
}

- (NSArray *)approveStateTFArray {
    if (!_approveStateTFArray) {
        _approveStateTFArray = @[@"请选择",@"同意",@"不同意"];//同意2，不同意3
    }
    return _approveStateTFArray;
}

- (void)setTipTitleLabelArray:(NSArray *)tipTitleLabelArray {
    _tipTitleLabelArray = tipTitleLabelArray;
}

- (void)setInfoTitleLabelArray:(NSArray *)infoTitleLabelArray {
    _infoTitleLabelArray = infoTitleLabelArray;
}

- (NSArray *)shenpiArray {
    if (!_shenpiArray) {
        _shenpiArray = @[@"审批状态：",@"审批意见："];
    }
    return _shenpiArray;
}

- (NSMutableArray *)infoTitleLabelArrayM {
    if (!_infoTitleLabelArrayM) {
        _infoTitleLabelArrayM = [[NSMutableArray alloc] init];
    }
    return _infoTitleLabelArrayM;
}

- (UITextView *)contentTV {
    if (!_contentTV) {
        _contentTV = [[UITextView alloc] init];
        _contentTV.layer.cornerRadius = 4;
        _contentTV.layer.masksToBounds = true;
        _contentTV.layer.borderWidth = 1;
        _contentTV.layer.borderColor = UIColor.grayColor.CGColor;
        _contentTV.delegate = self;
    }
    return _contentTV;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
